﻿using System;
using System.Collections.Specialized;
using System.IO;
using System.Net;

namespace QQWeiBoSDK
{
    class OAuthQQ : OAuthBase
    {
        public OAuthQQ()
        {
            Title = @"腾讯微博";
            LinkIconUrl = @"http://s1.t.itc.cn/mblog/pic/201101/5/16/m_12942176256762.png";
            OauthCallback = "null";
            RequestToken = "https://open.t.qq.com/cgi-bin/request_token";
            Authorize = "https://open.t.qq.com/cgi-bin/authorize";
            AccessToken = "https://open.t.qq.com/cgi-bin/access_token";
            Jpeg = "image/jpeg";
        }

        /// <summary>
        /// Generate a nonce
        /// </summary>
        /// <returns>32 long string</returns>
        public override string GenerateNonce()
        {
            return Guid.NewGuid().ToString("N");
        }

        public override void AccessTokenGet(string authToken, string verifier)
        {
            OauthCallback = string.Empty;
            base.AccessTokenGet(authToken,verifier);
        }

        internal override void SaveTokenAndTokenSecret()
        {
            SettingHelper.QQToken = Token;
            SettingHelper.QQTokenSecret = TokenSecret;
            SettingHelper.Save();
        }
        protected override void XAuthHeader(HttpWebRequest webRequest, NameValueCollection qs)
        {
            return;
        }

        protected override void MultipartformBody(NameValueCollection qs, byte[] boundarybytes, byte[] boundarybytes1, Stream requestStream, string formdataTemplate)
        {
            bool isfirstline = true;
            foreach (string key in qs.Keys)
            {
                if (isfirstline)
                {
                    requestStream.Write(boundarybytes1, 0, boundarybytes1.Length);
                    isfirstline = false;
                }
                else
                {
                    requestStream.Write(boundarybytes, 0, boundarybytes.Length);
                }

                string formitem = string.Format(formdataTemplate, key, qs[key]);
                byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
                requestStream.Write(formitembytes, 0, formitembytes.Length);
            }
            requestStream.Write(boundarybytes, 0, boundarybytes.Length);
        }
    }
}
